<?php

namespace App\Admin\Renderable;

use App\Models\Administrator;
use App\Models\UserGroup;
use Carbon\Carbon;
use Dcat\Admin\Grid;
use Dcat\Admin\Grid\LazyRenderable;
use Illuminate\Support\Facades\Cache;


class DispatchUserTable extends LazyRenderable
{

    public function grid(): Grid
    {
        // 获取外部传递的参数
        $q = Administrator::query()
            ->select(['id', 'name', 'online', 'username', 'dispatch_limit'])
            ->with(['departments' => function ($q) {
                $q->select(['id' , 'title'])->withPivot('is_manager');
            } , 'group' => function ($q) {
                $q->select(['id', 'name']);
            }])
            ->whereHas('roles', function ($query) {
                $query->where('slug', Administrator::DISPATCH_KEY);
            })
            ->orderBy('order');

        $users = data_get($this->payload, 'users');
        if ($users)
            $q->whereIn('id', $users);

        return Grid::make($q, function (Grid $grid) {
            $grid->column('id');
            $grid->column('name', '用户名');
            $grid->column('departments', '部门')->display(function ($val) {
                $str = "";
                foreach ($val as $item) {
                    $isManager = data_get($item, 'pivot.is_manager');
                    $color = $isManager ? '#C06156' : '#586cb1';
                    $str .= "
                        <span class='label' style='background:{$color};'>{$item['title']}</span>
                        ";
                }
                return $str;
            });
            $grid->column('group', '分组')->pluck('name')->label();

            $grid->column('_any_', '今天分配数量')
                ->display(function () {
                    $date = Carbon::today()->toDateString();
                    $var = Cache::get("$date.{$this->id}") ?? 0;
//                    if ($var)
//                        dd($var , $this->id);
                    return $var;
                });
            $grid->column('full_dispatch_limit', '本日总分配上限(包含临时)')
                ->display(function ($val) {
                    return $val;
                });
            $grid->column('online', '在线状态')->bool();

            $grid->quickSearch(['id', 'username', 'name']);

            $grid->paginate(100);
            $grid->disableActions();

            $grid->filter(function (Grid\Filter $filter) {
                $groupOptions = UserGroup::query()->select(['id', 'name'])->pluck('name', 'id');
                $filter->where('group_id', function ($query) {
                    if ($this->input) {
                        $query->whereHas('group', function ($q) {
                            $q->where('group_id', $this->input);
                        });
                    }
                }, '分组')->select($groupOptions)
                    ->width(4);
            });
        });
    }
}
